﻿#include "tcpclient.h"
#include "common.h"
#include <QHostAddress>
#include <QDebug>
#include <QMessageBox>

TcpClient::TcpClient() {
    isConnect = false;
    initConnect();
}

TcpClient::~TcpClient() {
    disconnect();
    if (tcpSocket != nullptr)
        tcpSocket->deleteLater();
}

bool TcpClient::initConnect() {
    if(isConnect) {
        return true;
    }
    tcpSocket = new QTcpSocket;
    tcpSocket->connectToHost(QHostAddress(HOST), PORT);
    qDebug() << "initConnect" << endl;

    // 设置超时连接时间
    isConnect = tcpSocket->waitForConnected(1 * 1000);

    // 连接状态变化触发
    QObject::connect(tcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
                     this, SLOT(slotStateChanged(QAbstractSocket::SocketState)));

    return isConnect;
}

QTcpSocket *TcpClient::getSocket() {
    return tcpSocket;
}

bool TcpClient::sendData(QString &data) {
    if (!isConnect)
        return false;

    // 数据做base64转码
    QByteArray base64 = data.toUtf8();
    QString le;
    // 预留8字节保存长度
    le.sprintf("%08d", base64.size());
    // 拼接数据 报文长度+报文
    base64 = le.toUtf8() + base64;
    // 发送数据
    tcpSocket->write(base64.data(), base64.size());
    return true;
}

bool TcpClient::readData(QString &readBuf) {
    if (!isConnect)
        return false;

//    char buf[9] = {0};
//    // 每次取8个字节长度
//    tcpSocket->read(buf, 8);
//    int len = atoi(buf);
//    // 保存数据缓冲区
//    char data[len + 1];
//    memset(data, 0, len + 1);

//    char data[MSG_MAX_SIZE];
//    memset(data, 0, MSG_MAX_SIZE);

//    // 读取指定长度
//    tcpSocket->read(data, MSG_MAX_SIZE);
    QByteArray data = tcpSocket->readAll();
    // base64转码
    readBuf.append(QByteArray::fromBase64(data));
    qDebug() << "data:" << data;
    qDebug() << "readData:" << readBuf;
    return true;
}

bool TcpClient::isConnected() {
    return isConnect;
}


void TcpClient::disconnectServer() {
    isConnect = false;

    if(!tcpSocket)
        return;

    if(tcpSocket->state() == QAbstractSocket::UnconnectedState || tcpSocket->waitForDisconnected(1000))
        return;
}

void TcpClient::slotStateChanged(QAbstractSocket::SocketState state) {
    switch (state) {
        case QAbstractSocket::SocketState::UnconnectedState: {
            isConnect = false;
        }
        break;

        case QAbstractSocket::SocketState::ConnectedState: {
            isConnect = true;
        }
        break;

        default:
            break;
    }

    emit connectChangeSignal(isConnect);
}
